from pymodis import convertmodis_gdal
import warnings
import time
from modis_utils import *
warnings.filterwarnings(action='ignore')


def merge_modis_to_tiff(tiff_list, output_dir, fill):
    min_x, max_y, max_x, min_y = get_extent(tiff_list[0])
    for in_fn in tiff_list[1:]:
        minx, maxy, maxx, miny = get_extent(in_fn)
        min_x = min(min_x, minx)
        min_y = min(min_y, miny)
        max_x = max(max_x, maxx)
        max_y = max(max_y, maxy)
    in_ds = gdal.Open(tiff_list[0])
    geotrans = list(in_ds.GetGeoTransform())
    geotrans = [min_x, geotrans[1], 0, max_y, 0, geotrans[5]]
    xsize = int((max_x - min_x) / geotrans[1] + 0.5)
    ysize = int((min_y - max_y) / geotrans[5] + 0.5)
    # band_type = in_ds.GetRasterBand(1).DataType
    driver = gdal.GetDriverByName('GTiff')
    out_ds = driver.Create(output_dir, xsize, ysize, 1, gdal.GDT_Float32)
    fill = float(in_ds.GetMetadata()['_FillValue'])
    out_ds.SetGeoTransform(geotrans)
    out_ds.SetProjection(in_ds.GetProjection())
    out_ds.GetRasterBand(1).SetNoDataValue(fill)
    out_ds.GetRasterBand(1).Fill(fill)
    for in_fns in tiff_list:
        in_ds = gdal.Open(in_fns)
        copy_into(out_ds, in_ds, 1, 1, fill)


if __name__ == '__main__':
    modis_path = 'F:/16satellite/data/china/'
    output_path = 'F:/16satellite/data/china_merge/'
    fill_none_data = -2
    yearList = os.listdir(modis_path)
    for year in yearList:
        oneYearDir = modis_path + str(year)
        dayList = os.listdir(oneYearDir)
        for day in dayList:
            start_time = time.time()
            oneDayDir = oneYearDir + '/' + str(day)
            hdfList = find_layers_files(oneDayDir, '.hdf')
            temp_tiff = output_path + '{0}/{1}/{2}'.format(year, day, 'temp')
            if not os.path.exists(temp_tiff):
                os.makedirs(temp_tiff)
            for one_modis_file in hdfList:
                (filename, extension) = os.path.splitext(one_modis_file)
                out_tiff = temp_tiff + '/{0}'.format(filename.split('\\')[-1])
                subset = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                mds = convertmodis_gdal.convertModisGDAL(
                    one_modis_file, out_tiff, subset, 0.1, outformat='GTiff',
                    epsg=4326, wkt=None, resampl='NEAREST_NEIGHBOR', vrt=False)
                mds.run()
            print('Convert modis to tiff is completed')
            tiff_list = find_layers_files(temp_tiff, '.tif')
            output_tiff_dir = output_path + '{0}/{1}/A{2}_{3}_global.tif'.format(year, day, year, day)
            if os.path.exists(output_tiff_dir):
                os.remove(output_tiff_dir)
                print('{} tiff file is exist and remove'.format(output_tiff_dir))
            merge_modis_to_tiff(tiff_list, output_tiff_dir, fill_none_data)
            if os.path.exists(temp_tiff):
                del_file(temp_tiff)
                os.rmdir(temp_tiff)
            print('Merge one day modis data to tiff is completed, cost time is: {} seconds'.format(
                time.time() - start_time))
